package mainWindow;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class InputField extends JTextField {
	private IndexPanel indexPanel;
	private String first;
	Color entryBG;
	public InputField(IndexPanel indexPanel)
	{
		this.indexPanel = indexPanel;
		entryBG = this.getBackground();
		this.getDocument().addDocumentListener(new DocumentListener(){
			public void changedUpdate(DocumentEvent e) {				
			}

			public void insertUpdate(DocumentEvent e) {
				search();
			}

			public void removeUpdate(DocumentEvent e) {
				search();
			}
			
		});
		this.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				Container container = getTopLevelAncestor();
				if (container instanceof MainFrame)
				{
					if (first != null && first.startsWith(getText()))
						((MainFrame)container).addWord(first);
				}
			}
		});
		
		this.addFocusListener(new FocusAdapter(){
			public void focusGained(FocusEvent e) {
				search();	
			}
		});
	}
	private void search()
	{
		String s = this.getText();
		first = indexPanel.changeFirst(s);
		indexPanel.showIndex();
		
		if (first.startsWith(s)){
			this.setBackground(entryBG);
		}
		else{
			this.setBackground(Color.PINK);
		}
	}
}
